//
//  Status.swift
//  新浪weibo
//
//  Created by test on 15/8/6.
//  Copyright © 2015年 test. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {

    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            // 判断数组中是否有数据 nil
            if pic_urls!.count == 0 {
                return
            }
            
            // 实例化数组
            storedPictureURLs = [NSURL]()
            
            // 遍历字典生成 url 的数组
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    /// `保存`配图的 URL 的数组
    private var storedPictureURLs: [NSURL]?
    
    
    var pictureURLs: [NSURL]? {
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }    //用户信息
    var user: User?
    //转发微博
    var retweeted_status:Status?
    // 行高缓存
    var rowHeight: CGFloat?
    
    class func loadStatus(finished: (dataList: [Status]?,error: NSError?) -> ()) {
        NetworkTools.sharedNetworkTools.loadStatus { (result, error) -> () in
            if error != nil {
                
                finished(dataList: nil, error: error)
                return
                
            }
            
            if let array = result?["statuses"] as? [[String:AnyObject]] {
                var list = [Status]()
                
                for dict in array {
                    
                    list.append(Status(dict:dict))
                    
                }
                self.cacheWebImage(list, finished: finished)
//                finished(dataList: list, error: nil)
                
            } else {
            
            finished(dataList: nil, error: nil)
            }
        }
    }
    
    private class func cacheWebImage(list:[Status],finished:(dataList:[Status]?,error:NSError?) -> ()) {
        let group = dispatch_group_create()
        var dataLength = 0
        
        for status in list {
            guard let urls = status.pictureURLs else {
                
               continue
            }
            
            for imageUrl in urls {
               dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    let data = UIImagePNGRepresentation(image)!
                    dataLength += data.length
                    
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存图片大小\(dataLength/1024)k")
            finished(dataList: list, error: nil)
        }
    }
    
    
    init(dict:[String:AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String:AnyObject] {
                user = User(dict: dict)
                
            }
            return
        }
        if key == "retweeted_status" {
            if let dict = value as? [String:AnyObject] {
            
            retweeted_status = Status(dict: dict)
            
            }
            return
        
        }
 
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description:String {
        let keys = ["created_at", "id", "text", "source", "pic_urls"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    
    
    }
    
}
